package org.cuit.lmq.controller;


import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.cuit.lmq.constants.enums.RedisKeyEnum;
import org.cuit.lmq.domain.common.Result;
import org.cuit.lmq.domain.dto.UserDto;
import org.cuit.lmq.domain.po.User;
import org.cuit.lmq.service.UserService;
import org.cuit.lmq.utils.RedisCache;
import org.cuit.lmq.utils.validate.MailUtil;
import org.cuit.lmq.utils.validate.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Seon
 * @since 2023-03-03
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/send/code")
    public Result<?> sendCode(@RequestParam("email") String email) {
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        String redisKey = RedisKeyEnum.CAPTCHA.getValue() + email;
        /*
         * redis主键为 captcha:2963095996@qq.com, 过期时间为五分钟。
         */
        redisCache.setCacheObject(redisKey, code, 5, TimeUnit.MINUTES);
        //发送邮件
        Thread mailThread = new Thread(new MailUtil(email, code));
        mailThread.start();
        log.info("验证码已发送, email = {}, code = {}", email, code);
        return Result.success("获取验证码成功，请及时查收哦");
    }


    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        if (ObjectUtils.isNull(user) || ObjectUtils.isNull(user.getUsername()) || ObjectUtils.isNull(user.getPassword())) {
            return Result.fail("用户信息错误，劝你不要乱来啊", HttpStatus.HTTP_UNAUTHORIZED);
        }
        String token = userService.login(user);
        if (null == token) {
            return Result.fail("用户认证失败", HttpStatus.HTTP_UNAUTHORIZED);
        }

        User userFullData = userService.getUserByName(user.getUsername());

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", userFullData);
        return Result.success(data);
    }

    @PostMapping("/signup")
    public Result<?> signup(@RequestBody UserDto userDto) {
        String code = userDto.getCode();
        if (!StringUtils.hasText(code)) {
            return Result.fail("验证码为空，请获取验证码", 0);
        }
        // 这里用validate_code: + email作为redis的key
        String redisKey = RedisKeyEnum.CAPTCHA.getValue() + userDto.getEmail();
        String validateCode = redisCache.getCacheObject(redisKey);

        if (validateCode == null) {
            return Result.fail("验证码已过期，请重新获取", 0);
        } else if (!validateCode.equals(code)) {
            return Result.fail("验证码错误", 0);
        }
        boolean signup = userService.signup(userDto);
        if (signup) {
            return Result.success("注册成功");
        } else {
            return Result.fail("注册失败", 0);
        }
    }


    @GetMapping("/logout")
    public Result<?> logout() {
        boolean logout = userService.logout();
        if (logout) {
            return Result.success(true);
        } else {
            return Result.fail("登出失败，非法token", 0);
        }
    }
}

